<style>
</style>
<template>
  <list_url ref="list_url" :config="config">
    <template #create_time="{row}">
      <div class="flex">
        <radio :config="row.config" v-model:value="row.value" button="1" :size="row.size"></radio>
        <date_between :name="row.name" config="Y-M-D" v-model:value="row.value" :size="row.size"></date_between>
      </div>
    </template>
    <template #object="{row}">
      <div style="width: 100%;" :title="row.title">
        <img style="height: 24px;width: 24px;object-fit: cover;float: left" :src="row.head_img" onclick="show_file(this.src)" />
        <p style="width: 100%;text-align: left;">{{row.title}}（数量x{{row.num}}）</p>
      </div>
    </template>
    <template #action="{row}">
      <el-button @click="to_edit(row)" size="small">详情</el-button>
      <el-button v-for="btn in row.btns" :type="btn.type" size="small" @click="btn.onclick(row)">{{ btn.title }}</el-button>
    </template>
  </list_url>
</template>
<script>
import {_href} from "@/js/s94_tool.js";
import {iframe} from "@/js/tool.js";

export default {
  props: ['__iframe'],
  data(){
    let app = this, btns = {}, is_del = this.$get('is_del');
    let model = {name:this.$get('model_name'), alias:this.$get('model_alias','')};
    function in_right_action(action){
      return app.in_right(app.camel_str(model.name)+'/'+action);
    }

    if (is_del){
      if(in_right_action('restore')) btns['恢复'] = function(){ app.$refs['list_url'].restore() }
      if(in_right_action('delete')) btns['彻底删除'] = function(){ app.$refs['list_url'].delete() }
    }else {
      if(in_right_action('add')) btns['添加'] = function(){ iframe('edit?'+app.param()) }
      // if(in_right_action('del')) btns['删除'] = function(){ app.$refs['list_url'].del() }
      // if(in_right_action('recycle')) btns['回收站'] = function(){ app.iframe('index?'+app.param({is_del:1})) }
      if(in_right_action('export')) btns['导出'] = function(){
        let param = s94Mjs.param_encode(app.$refs['list_url'].$refs['forms'].form_data());
        window.open(_href("/admin/"+model.name+"/order_export?"+param), '_blank')
      }
    }

    let action_map = {
      deliver: {title:'发货', onclick: app.to_deliver},
      take: {title:'收货', onclick: app.order_take},
      use: {title:'核销', onclick: app.order_use},
      refund_log: {title:'退款记录', onclick: app.to_refund_log},
      refund_action: {title:'审核退款', onclick: app.to_refund_action},
      refund: {title:'退款', onclick: app.refund},
      order_refund_direct: {title:'直接退款', onclick: app.order_refund_direct},
    }
    if (!in_right_action('order_deliver')) delete action_map.deliver;
    if (!in_right_action('order_take')) delete action_map.take;
    if (!in_right_action('order_use')) delete action_map.use;
    if (!app.in_right('OrderRefund/list')) delete action_map.refund_log;
    if (!app.in_right('OrderRefund/edit_action')) delete action_map.refund_action;
    if (!app.in_right('OrderRefund/edit_refund')) delete action_map.refund;

    function action_btns(row){
      let res = [];
      if (row.order_refund_id>0 && action_map.refund_log) res.push(action_map.refund_log);
      if (row.refund_status==0){
        if (row.status == 2 && action_map.deliver) res.push(action_map.deliver);
        if (row.status == 3 && action_map.take) res.push(action_map.take);
        if (row.status == 4 && action_map.use) res.push(action_map.use);
        if (row.status == "4_1" && action_map.use) res.push(action_map.use);
        res.push(action_map.order_refund_direct);
      }else {
        if (row.order_refund_status==0){
          res.push(action_map.refund_action);
        }else if((row.order_refund_status==3 && (row.order_refund_need_deliver==0||row.order_refund_deliver_no)) || row.order_refund_status==6) {
          res.push(action_map.refund);
        }
      }
      return app.decode_btns(res);
    }
    return {
      in_right_action: in_right_action,
      model: model,
      action_map: action_map,
      config: {
        api: '/admin/'+model.name+'/order_'+(is_del?'recycle':'list'),
        title: model.alias+"订单列表"+(is_del?'(已删除)':''),
        btns: btns,
        forms_config: {},
        list_cols: {},
        resdata: function(list){
          var order_refund_status_config = app.admin_config('status_alias_map.order_refund.status');
          s94Mjs.each(list, function (row){
            if (app.model.name == "legal_help" && row.status == 4){
              row.status = row.status+'_'+row.kf_confirm_status;
            }
            if (row.order_refund_status==3 && row.order_refund_need_deliver==1 && !row.order_refund_deliver_no){
              row.order_refund_status_alias = '待退货';
            }else {
              row.order_refund_status_alias = order_refund_status_config[row.order_refund_status];
            }
            row.user = JSON.stringify({nickname:row.user_nickname, phone:row.user_phone});
            if (row.refund_status==0) row.order_refund_status = null;
            row.btns = action_btns(row);
          })
          return list;
        },
        limit: 20,
        p: this.$get('p', 1),
      },
    }
  },
  methods: {
    param(data){
      data = data || {};
      data.model_name = this.model.name;
      data.model_alias = this.model.alias;
      return s94Mjs.param_encode(data);
    },
    to_edit(row){
      let can_edit = this.in_right_action('order_edit') && ~[0,row.tenant_id].indexOf(this.admin_config('this_tenant.id'))
      let param = { id: row.id }
      if (!can_edit) param['is_info'] = 1;
      this.iframe('edit?'+this.param(param))
    },
    to_deliver(row){
      return this.iframe('deliver?'+app.param({id:row.id}), {width:'750px'});
    },
    to_refund_log(row){
      this.iframe('/order/refund_log?'+this.param({id:row.id, model_id:this.model.id}))
    },
    to_refund_action(row){
      return this.iframe('/order_refund/edit?id='+row.order_refund_id, {width:'750px'});
    },
    order_take(row){
      let app = this;
      this.$confirm('是否执行 【'+app.action_map.take.title+'】 操作').then(()=>{
        ajax('/admin/'+app.model.name+'/order_take?ids='+row.id, function(res){
          app.$refs['list_url'].list();
        })
      }).catch(()=>{})
    },
    order_use(row){
      let app = this;
      this.$confirm('是否执行 【'+app.action_map.use.title+'】 操作').then(()=>{
        ajax('/admin/'+app.model.name+'/order_use?ids='+row.id, function(res){
          app.$refs['list_url'].list();
        })
      }).catch(()=>{})
    },
    refund(row){
      let app = this;
      function action(){
        ajax('/admin/order_refund/edit_refund?id='+row.order_refund_id, function(res){
          app.$refs['list_url'].list();
        })
      }
      if(!row.order_refund_need_deliver) return this.$confirm(`是否发起退款？`).then(()=>{
        action();
      }).catch(()=>{})
      if (!row.order_refund_deliver_no) return this.$message.error('需要客户退货后才能发起退款');
      this.$confirm(`此退款单需要用户退货，退货单号(${row.order_refund_deliver_no})，是否已收到货物`).then(()=>{
        action()
      }).catch(()=>{})
    },
    order_refund_direct(row){
      let app = this;
      this.confirm("是否确定退款？", function (){
        ajax('/admin/'+app.model.name+'/order_refund_direct?id='+row.id, function(res){
          app.$refs['list_url'].list();
        })
      })
    },
  },
  mounted() {
    let app = this;
    if (!this.__iframe) window['app'] = this;

    let field_width = {};
    ajax({url:'/admin/'+app.model.name+'/field_config?action=list&table=1', cache:true}, function(res){
      app.model = res.data.model;
      // document.title = '后台-'+app.model.alias+'订单-列表';
      var status_config = app.admin_config('status_alias_map.order.status');
      var refund_status_config = app.admin_config('status_alias_map.order.refund_status');

      let action_alias = app.model.action_alias || {};
      let status_map = {deliver:2, take:3, use:4};
      Object.keys(action_alias).forEach((k)=>{
        if (k in status_map) status_config[status_map[k]] = '待'+action_alias[k];
        if (k in app.action_map) app.action_map[k].title = action_alias[k];
      })

      status_config = app.decode_config(status_config);
      status_config.unshift({value:"", content:"全部"});
      refund_status_config = app.decode_config(refund_status_config);
      refund_status_config.unshift({value:"", content:"全部"});

      let forms_config = {
        create_time: {label:'下单时间',name:'where[create_time][between]',type:'date_between',add_radio:true,config:'Y-M-D',value:'',size:''},
        br1: {label:'',name:'',type:'br',value:''},
        use_time: {label:'核销时间',name:'where[use_time][between]',type:'date_between',add_radio:true,config:'Y-M-D',value:'',size:''},
        br11: {label:'',name:'',type:'br',value:''},
        order_refund_refund_time: {label:'退款时间',name:'where[order_refund.refund_time][between]',type:'date_between',add_radio:true,config:'Y-M-D',value:'',size:''},
        br12: {label:'',name:'',type:'br',value:''},
        status: {label:'订单状态',name:'where[status][eq]',type:'radio',config:status_config,value:'',button:true,size:''},
        br2: {label:'',name:'',type:'br',value:''},
        refund_status: {label:'退款状态',name:'where[refund_status][eq]',type:'radio',config:refund_status_config,value:'',button:true,size:''},
        br3: {label:'',name:'',type:'br',value:''},
        order_pay_order_no: {label:'订单编号',name:'where[order_pay.order_no][like]',type:'text_one',value:''},
        max_level_parent: {label:'首运营商',name:'where[user.max_level_parent_id][eq]',type:'list_id',config:"/user/index",value:'', no_table:true},
      };
      if (app.model.name == "legal_help"){
        forms_config.status.name = "";
        status_config.splice(5,0,{value:"4_0", content:"待客服确认"});
        status_config[6]["value"] = "4_1";

        forms_config.status.onchange = function (row, v){
          let arr = v.split('_');
          app.config.forms_config["_status_copy"].value = arr[0] || "";
          app.config.forms_config["kf_confirm_status"].value = arr[1] || "";
        }
        forms_config["_status_copy"] = {label:'订单状态',name:'where[status][eq]',type:'hidden',value:''};
        forms_config["kf_confirm_status"] = {label:'订单状态',name:'where[kf_confirm_status][eq]',type:'hidden',value:''};
      }
      let list_cols = [
        {name:'id', label:'ID', width:'65px', type:'hidden', fixed:'left'},
        {name:'order_pay_order_no', label:'订单号', type:'text_more', width:'100px'},
        {name:'user', label:'下单用户', type:'json_param', config:[{"name":"nickname","label":"昵称"},{"name":"phone","label":"电话"}], width:'140px', align:'left'},
        {name:'object', label:app.model.alias+'详情', type:'object', min_width:'200px'},
      ];

      s94Mjs.each(res.data.where, function(v){
        let key = v.name.replace('.','_')+'_'+v.method;
        forms_config[key] = Object.assign({
          label: v.label,
          name: `where[${v.name}][${v.method}]`,
          tips: v.tips,
          type: v.type,
          config: v.config,
          value: v.value
        },JSON.parse(v.config_extend||'{}'));
      })
      app.config.forms_config = forms_config;
      s94Mjs.each(res.data.cols, function(v){
        let name = v.name.replace('.','_');
        let row = Object.assign({
          name: name,
          label: v.label,
          type: v.type || '',
          config: v.config,
          width: field_width[name] || '',
        }, JSON.parse(v.list_props||'[]'))
        list_cols.push(row);
      })
      list_cols.push({name:'pay_money', label:'支付金额', width:'70px'});
      list_cols.push({name:'order_pay_pay_type', label:'支付方式', width:'70px', type:'select_one', config:app.admin_config('status_alias_map.order_pay.pay_type',[])});
      list_cols.push({name:'status', label:'状态', width:'70px', type:'select_one', config:status_config});
      list_cols.push({name:'order_refund_status_alias', label:'退款状态', width:'70px'});
      list_cols.push({name:'create_time', label:'下单时间', width:'165px'});
      list_cols.push({name:'use_time', label:'核销时间', width:'165px'});
      list_cols.push({name:'order_refund_refund_time', label:'退款时间', width:'165px'});
      if (!app.admin_config('this_tenant.id')){
        list_cols.push({name:'tenant_id', label:'租户', width:'65px', fixed:'right'});
        delete app.config.btns['添加'];
      }
      list_cols.push({name:'action', label:'操作', width:'140px', type:'action', fixed:'right'});
      app.config.list_cols = list_cols;
      setTimeout(function(){app.$refs['list_url'].$refs['forms'].set_init_value()})
      return false;
    })
  }
}
</script>
